package app

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/atotto/clipboard"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type ClipboardApp struct {
	ctx        context.Context
	cancelFunc context.CancelFunc
	mu         sync.Mutex
}

func NewClipboard() *ClipboardApp {
	return &ClipboardApp{}
}

func (a *ClipboardApp) Startup(ctx context.Context) {
	a.ctx = ctx
}

func (a *ClipboardApp) Shutdown(ctx context.Context) {
	// Do nothing
}

func (a *ClipboardApp) StartClipboard() {
	fmt.Println("开启剪贴板监听")
	a.mu.Lock()
	defer a.mu.Unlock()
	ctx, cancel := context.WithCancel(context.Background())
	a.cancelFunc = cancel

	go func() {
		lastText, _ := clipboard.ReadAll() // 初始化为当前剪贴板内容
		for {
			select {
			case <-ctx.Done():
				return
			default:
				text, err := clipboard.ReadAll()
				if err != nil {
					fmt.Println("Error reading clipboard:", err)
					time.Sleep(3 * time.Second)
					continue
				}
				if text != lastText {
					lastText = text
					runtime.EventsEmit(a.ctx, "clipboard", text)
				}

				time.Sleep(2 * time.Second)
			}
		}
	}()
}

func (a *ClipboardApp) StopClipboard() {
	fmt.Println("关闭剪贴板监听")
	a.mu.Lock()
	defer a.mu.Unlock()
	if a.cancelFunc != nil {
		a.cancelFunc()
		a.cancelFunc = nil
	}
}
